package com.backup.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileUtil {
	/**
	 * 拷贝文件夹
	 * @param targetFolderPath
	 * @param srcFolderPath
	 * @throws IOException
	 */
	public static void copyDirectiory(String srcFolderPath, String targetFolderPath) throws IOException {
		(new File(targetFolderPath)).mkdirs();
		File[] childrenFiles = (new File(srcFolderPath)).listFiles();
		for (int i = 0; i < childrenFiles.length; i++) {
			if (childrenFiles[i].isFile()) {
				copyFile(childrenFiles[i], new File(targetFolderPath + File.separator + childrenFiles[i].getName()));
			}
			if (childrenFiles[i].isDirectory()) {
				copyDirectiory(srcFolderPath + File.separator + childrenFiles[i].getName(),
						targetFolderPath + File.separator + childrenFiles[i].getName());
			}

		}
	}

	/**
	 * 拷贝文件
	 * @param srcFile
	 * @param targetFile
	 * @throws IOException
	 */
	public static void copyFile(File srcFile, File targetFile) throws IOException {
		if (targetFile.exists()) {
			targetFile.delete();
		} else if (targetFile.getParentFile()!=null && !targetFile.getParentFile().exists()) {
			(targetFile.getParentFile()).mkdirs();
		}
		targetFile.createNewFile();
		FileInputStream input = null;
		FileOutputStream output = null;
		try {
			input = new FileInputStream(srcFile);
			output = new FileOutputStream(targetFile);
			byte[] b = new byte[1024 * 5];
			int len;
			while ((len = input.read(b)) != -1) {
				output.write(b, 0, len);
			}
		} catch (IOException e) {
			throw e;
		} finally {
			try {
				output.flush();
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				output.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				targetFile.setLastModified(srcFile.lastModified());//设置最新更新时间
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			try {
				input.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
